/**
 * message-service
 * @authors 杨兴洲（of2502）
 * @date    2017/4/26 0026 19:31
 * @version 1.0
 */

import Message from "../model/message";

export default class MessageService {
    /**
     * 保存消息
     * @param message
     * @returns {Promise<string>}
     */
    static save(message: any): Promise<string> {
        return Message.create(message).then((doc: any) => doc.id);
    }

    /**
     * 获取列表
     */
    static async getList({appID, msgType = "text", cate = "all", page, pageSize}): Promise<any> {
        // type: all || star || noReply
        const filter: any = {};
        if (cate === "star") filter.isStar = true;
        if (cate === "noReply") filter["replyList.0"] = {"$exists": false}; // todo: 查询数组长度 > 1
        const total = await Message.count({toUser: appID, msgType, ...filter});
        const list = await Message.find({toUser: appID, msgType, ...filter}, {"__v": 0})
            .sort({createdAt: -1})
            .skip(pageSize * (page - 1)).limit(+pageSize);

        return {total, list};
    }

    /**
     * 获取详细信息
     */
    static async getDetail(msgID?: string): Promise<any> {
        return await Message.findOne({_id: msgID});
    }

    /**
     * 添加replyList
     * @param replyFrom:
     * @param replyTo:
     * @returns {Promise<any>}
     */
    static async updateReplyList({replyFrom, replyTo}): Promise<any> {
        return await Message.findOneAndUpdate({_id: replyTo}, {
            "$addToSet": {replyList: replyFrom}
        }, {"new": true});
    }

    /**
     * 切换收藏
     * @param msgID
     * @param isStar
     * @returns {Promise<any>}
     */
    static async toggleStar({msgID, isStar}): Promise<any> {
        if (isStar === "1" || isStar === "0") isStar = !!+isStar;
        if (isStar === undefined) {
            const data: any = await MessageService.getDetail(msgID);
            isStar = !data.isStar;
        }

        return await Message.findOneAndUpdate({_id: msgID}, {isStar}, {"new": true});
    }

    /**
     * 数据统计
     */
    static async getCount({appID, msgType = "text", beginDate, endDate}: { appID: string, msgType: string, beginDate?: string, endDate?: string }) {
        /*todo: 等待使用聚合重构*/
        let filter: any = {};
        const createdAt: any = {};
        if (beginDate) createdAt["$gte"] = new Date(beginDate);
        if (endDate) createdAt["$lte"] = new Date(+new Date(endDate) + 24 * 60 * 60 * 1000); // +1天 24:00
        if (beginDate || endDate) filter = {createdAt};
        if (msgType !== "all") filter = {...filter, msgType};
        let allSize = await Message.count({toUser: appID, ...filter});
        let noReplySize = await Message.count({toUser: appID, "replyList.0": {"$exists": false}, ...filter});
        let starSize = await Message.count({toUser: appID, isStar: true, ...filter});
        return {
            all: allSize,
            isReply: allSize - noReplySize,
            noReply: noReplySize,
            star: starSize
        }
    }

    static async getSendCount({appID, msgType = "text", beginDate, endDate}: { appID: string, msgType: string, beginDate?: string, endDate?: string }) {
        let filter: any = {};
        const createdAt: any = {};
        if (beginDate) createdAt["$gte"] = new Date(beginDate);
        if (endDate) createdAt["$lte"] = new Date(+new Date(endDate) + 24 * 60 * 60 * 1000); // +1天 24:00
        if (beginDate || endDate) filter = {createdAt};
        if (msgType !== "all") filter = {...filter, msgType};
        let allSize = await Message.count({fromUser: appID, ...filter});
        return {
            count: allSize,
        }
    }
}
